import { FC, Suspense, useEffect } from 'react'
import * as Type from "@/utils/index"
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom"
import NProgress from "nprogress"
import "nprogress/nprogress.css"

type Props = {
    routerConfig: Type.RouterList,
    mode?: Type.RouterType
}

const BeforeRouter = ({ Com, title }: { Com: string, title: string }) => {
    useEffect(() => {
        NProgress.start()
        document.title = title
        NProgress.done()
    }, [title])
    return <Com />
}

const Router: FC<Props> = ({ routerConfig }) => {
    const renderRouter = (arr: Type.RouterList) => {
        return arr?.map((item: Type.RouterItem, index: number) => {
            return <Route
                key={index}
                path={item.path}
                element={item.to ? <Navigate to={item.to} /> : <BeforeRouter Com={item.element} title={item.title as string} />}
            >
                {item.children && renderRouter(item.children)}
            </Route>
        })
    }
    return <Suspense fallback={<>路由加载中...</>}>
        <Routes>
            {renderRouter(routerConfig)}
        </Routes>
    </Suspense>
}

// history路由模式
const RouterView: FC<Props> = ({ routerConfig, mode }) => {
    if (mode === "history") {
        return (
            <BrowserRouter>
                <Router routerConfig={routerConfig} />
            </BrowserRouter>
        )
    }
}

export default RouterView
